using UnityEngine;
using QFramework;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class Ball : ViewController
	{
		void Start()
		{
			SelfRigidbody2D.velocity = 
			new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)) *
			Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2);

			Global.SuperBasketBall.RegisterWithInitValue(unlocked => 
			{
				if(unlocked)
				{
					this.LocalScale(3); // 放大
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			HurtBox.OnTriggerEnter2DEvent(collider =>
			{
				var hurtBox = collider.GetComponent<HurtBox>();
				if(hurtBox)
				{
					if(hurtBox.Owner.CompareTag("Enemy"))
					{
						var enemy = hurtBox.Owner.GetComponent<IEnemy>();
						var damageTimes = Global.SuperBasketBall.Value ? Random.Range(2, 3 + 1) : 1; // 超级篮球的伤害倍数生成2-4倍
						DamageSystem.CalculateDamage(Global.BasketBallDamage.Value * damageTimes, enemy); // 计算伤害基础伤害值乘以伤害倍数
						
						// 击退效果
						if(Random.Range(0, 1f) < 0.5f && collider && collider.attachedRigidbody && Player.Default)
						{
							collider.attachedRigidbody.velocity = 
							collider.NormalizedDirection2DFrom(this).normalized * 5 +
							collider.NormalizedDirection2DFrom(Player.Default) * 10; // 击退效果
						}
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

        void OnCollisionEnter2D(Collision2D other)
        {
            var normal = other.GetContact(0).normal; // 获取碰撞点的法线向量
			if(normal.x > normal.y)
			{
				SelfRigidbody2D.velocity = new Vector2(SelfRigidbody2D.velocity.x,
				Mathf.Sign(SelfRigidbody2D.velocity.y) * Random.Range(0.5f, 1.5f) *
				Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2)); // 垂直方向速度保持不变，水平方向速度随机

				SelfRigidbody2D.angularVelocity = Random.Range(-360, 360); // 随机旋转角度
			}
			else
			{
				var rb = SelfRigidbody2D;
				rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * Random.Range(0.5f, 1.5f) * Random.Range(
				Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2),
				rb.velocity.y); // 水平方向速度保持不变，垂直方向速度随机

				rb.angularVelocity = Random.Range(-360f, 360f); // 随机旋转角度
			}

			AudioKit.PlaySound(Sfx.BALL);
        }
    }
}
